import sun.misc.BASE64Encoder

import java.security.Key
import java.security.KeyPair
import java.security.KeyStore
import java.security.PrivateKey
import java.security.cert.Certificate

public class ExportPrivateKey {

    File keyStoreFile
    String keyStoreType = "JKS"
    char[] password = "changeit".toCharArray()
    String alias = "tomcat"
    File exportedFile = new File("W:/test/tomcatpriv.pem")


    public ExportPrivateKey(File keyStoreFile) {
        this.keyStoreFile = keyStoreFile
    }

    public ExportPrivateKey() {
        this.keyStoreFile = new File(System.getProperty("user.home"), ".keystore")
    }

    public static KeyPair getPrivateKey(KeyStore keyStore, String alias, char[] password) throws Exception {
        Key key = keyStore.getKey(alias, password)
        if (key instanceof PrivateKey) {
            Certificate cert = keyStore.getCertificate(alias)
            return new KeyPair(cert.getPublicKey(), key)
        }
    }

    public void export() throws Exception {
        KeyStore keyStore = KeyStore.getInstance(keyStoreType)
        BASE64Encoder encoder = new BASE64Encoder()
        keyStore.load(new FileInputStream(keyStoreFile), password)
        KeyPair keyPair = getPrivateKey(keyStore, alias, password)
        PrivateKey privateKey = keyPair.getPrivate()
        String encoded = encoder.encode(privateKey.getEncoded())

        exportedFile.withPrintWriter { PrintWriter out ->
            out.print Arrays.asList("--BEGIN PRIVATE KEY--", encoded, "--END PRIVATE KEY--").join("\n")
        }

    }



    public static void main(String... args) {
        ExportPrivateKey exportPrivateKey = new ExportPrivateKey()
        exportPrivateKey.export()
        println "Private exported to ${exportPrivateKey.exportedFile.absolutePath}"
    }

}